local ExcelKill = require("excel.Skill").Kill
local Timer = require("core.Timer")
local Msg = require("core.Msg")
local Obj = require("core.Obj")
local Buffer = require("buffer.Buffer")

function onKill(human)
    local interval  = getInterval(human)
    local now = Timer.now

    if now - human.killLastTime > interval then
        human.killCount = 0
    end

    human.killCount = human.killCount + 1
    human.killLastTime = now

    local type = 0
    local data = killNumConfigDic[human.killCount]
    if data then
        v = data[2]
        if canAddBuf(human, data[1]) then
            type = data[1]
            for _, bufID in ipairs(v.bufID) do
                Buffer.add(bufID, human, human)
            end
        end
    end

    local mm = Msg.gc.GC_SKILL_KILL_NUM
    mm.count = human.killCount
    mm.type = type 
    mm.interval = getInterval(human)
    Msg.send(mm, human.fd)
end

function getInterval(human)
    local v
    for i = 1, #ExcelKill do
        v = ExcelKill[i]
        if human.killCount < v.num then
            return v.interval
        end
    end
    return v.interval
end

bufs = {}
killNumConfigDic = {}
function init()
    for i = 1, #ExcelKill do
        local config = ExcelKill[i]
        bufs[i] = bufs[i] or {}
        killNumConfigDic[config.num] = {[1]=i, [2]=config}
        for j = i + 1, #ExcelKill do
            local v = ExcelKill[j]
            for _, bufID in ipairs(v.bufID) do
                bufs[i][bufID] = true
            end
        end
    end
end

function canAddBuf(human, type)
    local dic = bufs[type]
    local bufList, len = Obj.getBuf(human)
    for i = len - 1, 0, -1 do
        local buf = bufList[i]
        if buf.id ~= 0 and dic[buf.id] then
            return false
        end
    end
    return true
end

init()
